package com.itheima.observer.demo;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zzw
 * @date 2025/10/25
 * @description 被观察者基类
 */
public class Subject {
    private final List<Observer> observers = new ArrayList<>();
    private boolean changed = false;

    public void addObserver(Observer observer) {
        if (observer == null) {
            throw new NullPointerException("Observer cannot be null");
        }
        if (!observers.contains(observer)) {
            observers.add(observer);
        }
    }

    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    public void notifyObservers() {
        notifyObservers(null);
    }

    public void notifyObservers(Object arg) {
        if (hasChanged()) {
            for (Observer observer : observers) {
                observer.update(this, arg);
            }
            clearChanged();
        }
    }

    protected void setChanged() {
        changed = true;
    }

    protected void clearChanged() {
        changed = false;
    }

    public boolean hasChanged() {
        return changed;
    }

    public int countObservers() {
        return observers.size();
    }
}
